﻿//#define TEST_SDK

#if (!UNITY_EDITOR || TEST_SDK) && WEIXINMINIGAME

using System;
using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using KuiHuaBaoDian.SDK.Serializable;
using WeChatWASM;

namespace KuiHuaBaoDian.SDK {

    public static partial class API {

        private partial class Implementation {

            private Func<string> m_GetQueryFunc;
            private IReadOnlyList<ShareImageSetting> m_ShareImageSettingList;

            public UniTask InitializeShare(Func<string> getQueryFunc = null, IEnumerable<ShareImageSetting> settings = null) {
                m_GetQueryFunc = getQueryFunc;
                m_ShareImageSettingList = settings?.ToArray();

                WXBase.OnShareAppMessage(new WXShareAppMessageParam {
                    query = m_GetQueryFunc?.Invoke(),
                }, action => {
                    if (m_ShareImageSettingList?.Count > 0) {
                        var randomIndex = UnityEngine.Random.Range(0, m_ShareImageSettingList.Count);
                        var shareImageSetting = m_ShareImageSettingList[randomIndex];
                        var param = new WXShareAppMessageParam {
                            query = m_GetQueryFunc?.Invoke(),
                            imageUrlId = shareImageSetting.Key,
                            imageUrl = shareImageSetting.URL,
                        };
                        action.Invoke(param);
                    }
                });
                return UniTask.CompletedTask;
            }

            public UniTask<bool> Share() {
                if (m_ShareImageSettingList?.Count > 0) {
                    var randomIndex = UnityEngine.Random.Range(0, m_ShareImageSettingList.Count);
                    var shareImageSetting = m_ShareImageSettingList[randomIndex];
                    WX.ShareAppMessage(new ShareAppMessageOption {
                        query = m_GetQueryFunc?.Invoke(),
                        imageUrlId = shareImageSetting.Key,
                        imageUrl = shareImageSetting.URL,
                    });
                } else {
                    WX.ShareAppMessage(new ShareAppMessageOption {
                        query = m_GetQueryFunc?.Invoke(),
                    });
                }
                return UniTask.FromResult(true);
            }
        }
    }
}
#endif